#include "chatwindow.h"
#include "ui_chatwindow.h"
#include "messagesession.h"
#include "chattextedit.h"
#include <QGraphicsView>
#include <QGraphicsPixmapItem>
#include <QSortFilterProxyModel>
#include <QKeyEvent>
#include "chattablemodel.h"

CUSTOM_EVENT_MAP(ChatWindow){
    //checkEvent<MessageEvent, onMessageReceived, messageItem()>(EVENT_MESSAGE_RECEIVED, event);
    CUSTOM_EVENT_WITH_PARAM(EVENT_MESSAGE_RECEIVED, onMessageReceived, MessageEvent, messageItem())
}


ChatWindow::ChatWindow(QWidget *parent) :
    QWidget(parent),
    session(NULL),
    ui(new Ui::ChatWindow),
    bFirst(true)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_MacBrushedMetal, true);
}

ChatWindow::ChatWindow(ChatWindow const& val) :
        QWidget((QWidget*)val.parent()),
        session(NULL),
        ui(new Ui::ChatWindow),
        bFirst(true)
{
    ui->setupUi(this);
    setAttribute(Qt::WA_MacBrushedMetal, true);
    copy(val);
}

ChatWindow& ChatWindow::copy(ChatWindow const& val)
{
    contact = val.contact;
    return *this;
}

ChatWindow& ChatWindow::operator=(ChatWindow const& val)
                     {
    return copy(val);
}

ChatWindow::~ChatWindow()
{
    delete ui;
}

bool ChatWindow::operator==(ChatWindow const& val)
{
    return contact==val.contact;
}

void	ChatWindow::closeEvent ( QCloseEvent * event )
{
    session->close();

    CloseChatWindowEvent* e = new CloseChatWindowEvent(*this);
    QCoreApplication::postEvent(eventHandler, e);

    //XmppManager::instance().closeSession(session);
}

void ChatWindow::initializeTableModel()
{
    table = QSharedPointer<ChatTableModel>(new ChatTableModel(messageList, tableView));
    //table = std::tr1::shared_ptr<ChatTableModel>(new ChatTableModel(messageList, tableView));
    tableView->setShowGrid(false);
    tableView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);

    //tableView->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
    tableView->horizontalHeader()->setStretchLastSection(true);
    tableView->verticalHeader()->hide();
    tableView->horizontalHeader()->hide();

    tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    proxyModel = QSharedPointer<QSortFilterProxyModel>(new QSortFilterProxyModel(tableView));
    proxyModel->setSourceModel(table.data());
    proxyModel->setDynamicSortFilter(true);

    tableView->setModel(proxyModel.data());
    item = QSharedPointer<ChatItemDelegate>(new ChatItemDelegate(tableView));
    tableView->setItemDelegate(item.data());
    tableView->setColumnWidth(0, 50);
    tableView->setColumnWidth(2, 50);
    QHeaderView* headerView = tableView->verticalHeader();
    headerView->setResizeMode(QHeaderView::ResizeToContents);


}

void ChatWindow::initialize()
{
    profileView = qFindChild<QGraphicsView*>(this, "graphicsView");
    labelName = qFindChild<QLabel*>(this, "labelName");
    textEditMessage = qFindChild<ChatTextEdit*>(this, "textEditMessage");
    tableView = qFindChild<QTableView*>(this, "tableView");

    QString strDisplayName, strTitle;
    strDisplayName = QString("%1 (%2)").arg(contact.name().c_str()).arg(contact.jid().c_str());
    strTitle = QString("Conversation with %1").arg(contact.name().c_str());
    setWindowTitle(strTitle);

    labelName->setText(strDisplayName);
    profileView->setScene(&scene);

    profileImage = contact.image().scaled(50,50,Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    scene.addPixmap(profileImage);

    session->setEventHandler(this);

    initializeTableModel();
    item->setContactProfileImage(contact.scaledImage());

}

void  ChatWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return)
    {
        on_sendButton_clicked();
    }

}

bool ChatWindow::event(QEvent *myEvent)
{
    if (myEvent->type() == QEvent::Show)
    {
        if (bFirst)
        {
            bFirst = false;
            initialize();
        }
    }
    return QWidget::event(myEvent);
}



void ChatWindow::on_sendButton_clicked()
{
    MessageItem item;
    item.setMessage(textEditMessage->toPlainText());
    item.setJid(tr(""));
    item.setTimeStamp(QDateTime::currentDateTime());
    table->addMessage(item);

    tableView->scrollToBottom();
    session->send(item.getMessage());
    textEditMessage->setPlainText("");


}

void ChatWindow::onMessageReceived(MessageItem& item)
{
    table->addMessage(item);
    tableView->scrollToBottom();
}

